package org.lanqiao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.lanqiao.entity.Category;
import org.lanqiao.service.CategoryService;
import org.lanqiao.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategroyController {

    @Autowired
    private CategoryService categoryService;


    /**
     * 添加分类
     * @param category
     * @return
     */
    @PostMapping
    public Result<String> addCategory(@RequestBody Category category){
        categoryService.save(category);
        return Result.success("新增分类成功");
    }


    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page , int pageSize){
        //分页构造器
        Page<Category> page1 = new Page<>(page , pageSize);

        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper();

        //排序
        queryWrapper.orderByAsc(Category :: getSort);
        categoryService.page(page1 , queryWrapper);
        return Result.success(page1);

    }

    /**
     * 根据id删除分类菜品
     * @param id
     * @return
     */
    @DeleteMapping
    public Result<String> deleteCategoryById(@RequestParam("ids") Long id){

        //categoryService.removeById(id);
        categoryService.remove(id);
        return Result.success("删除成功");
    }

    /**
     * 根据id修改分类信息
     * @param category
     * @return
     */
    @PutMapping
    public Result<String> updateCategoryById(@RequestBody Category category){
        categoryService.updateById(category);
        return Result.success("修改分类成功");
    }


    /**
     * 查询所有分类
     * @return
     */
    @GetMapping("/list")
    public Result<List<Category>> getAll(Category category){
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq( category.getType() != null,"type" , category.getType());

        //排序
        queryWrapper.orderByAsc("sort").orderByDesc("update_time");
        List<Category> list = categoryService.list(queryWrapper);
        return Result.success(list);

    }
}


